// pages/edit-profile/edit-profile.js
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const { regionSelector } = require('../../utils/region.js');
const app = getApp();

Page({
  data: {
    // 当前选中的Tab
    selectedTab: 'profile',
    
    // 个人资料表单
    profileForm: {
      userNum: 0,
      avatar: '',
      name: '',
      gender: '',
      height: '',
      weight: '',
      birthDate: '',
      maritalStatus: '',
      assets: {
        annualIncome: '',
        car: '',
        house: ''
      },

  // 使用卡通头像（男/女）
  onUseCartoonAvatar(e) {
    const type = e.currentTarget.dataset.type; // male | female
    // 如果你后续放入更精致的卡通图，请将路径替换为对应文件
    const malePath = '/assets/images/male_young_student.png';
    const femalePath = '/assets/images/male_young_normal.jpeg';
    const path = type === 'male' ? malePath : femalePath;
    this.setData({ 'profileForm.avatar': path });
  },

  // 头像加载失败时的兜底处理
  onAvatarError() {
    try {
      const gender = this.data.profileForm.gender || '女';
      const fallback = gender === '男' ? '/assets/images/male_young_normal.jpeg' : '/assets/images/female_young_normal.jpeg';
      this.setData({ 'profileForm.avatar': fallback });
    } catch (e) {
      // 静默失败
    }
  },
      education: '',
      occupation: '',
      isPartyMember: false,
      hometown: '',
      currentResidence: '',
      familyMembers: {
        familyType: '',
        fatherDetail: {
          age: '',
          desc: ''
        },
        motherDetail: {
          age: '',
          desc: ''
        },
        otherDetail: []
      }
    },
    
    // 择偶标准表单
    preferenceForm: {
      userNum: 0,
      standards: '',
      ageRange: {
        minAge: 18,
        maxAge: 60
      },
      heightRange: {
        minHeight: 150,
        maxHeight: 200
      },
      weightRange: {
        minWeight: 80,
        maxWeight: 200
      },
      incomeRange: {
        minIncome: 0,
        maxIncome: 100
      },
      educationRange: {
        minEducation: '',
        maxEducation: ''
      },
      occupationRequire: [],
      currentResidenceRequired: [],
      hometownRequired: [],
      personalityTraits: [],
      otherRequired: []
    },
    
    // 选项数据
    genderOptions: [],
    maritalStatusOptions: [],
    educationOptions: [],
    occupationOptions: [],
    carStatusOptions: [],
    houseStatusOptions: [],
    hometownOptions: [],
    residenceOptions: [],
    
    // 省市区三级联动数据
    provinceOptions: [],
    // 籍贯相关
    hometownCityOptions: [],
    hometownDistrictOptions: [],
    hometownProvinceIndex: 0,
    hometownCityIndex: 0,
    hometownDistrictIndex: 0,
    hometownSelectedText: '',
    // 现居地相关
    residenceCityOptions: [],
    residenceDistrictOptions: [],
    residenceProvinceIndex: 0,
    residenceCityIndex: 0,
    residenceDistrictIndex: 0,
    residenceSelectedText: '',
    
    // 常见地址快速选择
    commonHometownAddresses: [],
    commonResidenceAddresses: [],
    
    // 选择器索引
    maritalStatusIndex: 0,
    educationIndex: 0,
    occupationIndex: 0,
    carStatusIndex: 0,
    houseStatusIndex: 0,
    hometownIndex: 0,
    residenceIndex: 0,
    minEducationIndex: 0,
    maxEducationIndex: 0,
    
    // 标签输入
    personalityTraitInput: '',
    otherRequiredInput: '',
    
    // 状态
    loading: true,
    submitting: false
  },

  onLoad(options) {
    console.log('编辑资料页面加载');
    this.initData();
    this.loadUserData();
  },

  onShow() {
    console.log('编辑资料页面显示');
  },

  // 初始化数据
  initData() {
    const constants = app.globalData.constants;
    const currentUser = app.globalData.currentUser;
    
    // 初始化省市区数据
    const provinceOptions = regionSelector.getProvinces();
    const hometownCityOptions = regionSelector.getCitiesByProvince(provinceOptions[0]);
    const hometownDistrictOptions = regionSelector.getDistrictsByCity(provinceOptions[0], hometownCityOptions[0]);
    const residenceCityOptions = regionSelector.getCitiesByProvince(provinceOptions[0]);
    const residenceDistrictOptions = regionSelector.getDistrictsByCity(provinceOptions[0], residenceCityOptions[0]);
    
    // 初始化常见地址
    const commonHometownAddresses = regionSelector.getCommonAddresses('hometown');
    const commonResidenceAddresses = regionSelector.getCommonAddresses('residence');
    
    this.setData({
      genderOptions: constants.genders,
      maritalStatusOptions: constants.maritalStatus,
      educationOptions: constants.educations,
      occupationOptions: constants.occupations,
      carStatusOptions: constants.carStatus,
      houseStatusOptions: constants.houseStatus,
      hometownOptions: constants.hometowns,
      residenceOptions: constants.residences,
      
      // 省市区数据
      provinceOptions: provinceOptions,
      hometownCityOptions: hometownCityOptions,
      hometownDistrictOptions: hometownDistrictOptions,
      residenceCityOptions: residenceCityOptions,
      residenceDistrictOptions: residenceDistrictOptions,
      
      // 常见地址
      commonHometownAddresses: commonHometownAddresses,
      commonResidenceAddresses: commonResidenceAddresses,
      
      'profileForm.userNum': currentUser.userNum,
      'preferenceForm.userNum': currentUser.userNum
    });
  },

  // 加载用户数据
  async loadUserData() {
    try {
      this.setData({ loading: true });
      
      // 并行加载用户资料和择偶标准
      await Promise.all([
        this.loadUserProfile(),
        this.loadMatePreference()
      ]);
      
    } catch (error) {
      console.error('加载用户数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载用户资料
  async loadUserProfile() {
    try {
      const currentUser = app.globalData.currentUser;
      
      // 从API加载用户资料
      const response = await api.getUserProfile(currentUser.userNum);
      
      if (response && response.code === 0 && response.data && response.data.length > 0) {
        const profile = response.data[0];
        this.setData({
          profileForm: {
            ...this.data.profileForm,
            ...profile,
            avatar: profile.avatar || util.getDefaultAvatar(profile.gender),
            createUser: currentUser.userNum.toString(),
            modifyUser: currentUser.userNum.toString()
          }
        });
      }
      
      // 更新选择器索引
      this.updatePickerIndexes();
      
    } catch (error) {
      console.error('加载用户资料失败:', error);
      throw error;
    }
  },

  // 加载择偶标准
  async loadMatePreference() {
    try {
      const currentUser = app.globalData.currentUser;
      
      // 从API加载择偶标准
      const response = await api.queryMatePreference(currentUser.userNum);
      
      if (response && response.code === 0 && response.data && response.data.length > 0) {
        const preference = response.data[0];
        this.setData({
          preferenceForm: {
            ...this.data.preferenceForm,
            ...preference
          }
        });
      }
      
      // 更新择偶标准的选择器索引
      this.updatePreferenceIndexes();
      
    } catch (error) {
      console.error('加载择偶标准失败:', error);
      throw error;
    }
  },

  // 更新选择器索引
  updatePickerIndexes() {
    const { profileForm, maritalStatusOptions, educationOptions, occupationOptions, carStatusOptions, houseStatusOptions, hometownOptions, residenceOptions } = this.data;
    
    this.setData({
      maritalStatusIndex: maritalStatusOptions.indexOf(profileForm.maritalStatus),
      educationIndex: educationOptions.indexOf(profileForm.education),
      occupationIndex: occupationOptions.indexOf(profileForm.occupation),
      carStatusIndex: carStatusOptions.indexOf(profileForm.assets.car),
      houseStatusIndex: houseStatusOptions.indexOf(profileForm.assets.house),
      hometownIndex: hometownOptions.indexOf(profileForm.hometown),
      residenceIndex: residenceOptions.indexOf(profileForm.currentResidence)
    });
  },

  // 更新择偶标准选择器索引
  updatePreferenceIndexes() {
    const { preferenceForm, educationOptions } = this.data;
    
    this.setData({
      minEducationIndex: educationOptions.indexOf(preferenceForm.educationRange.minEducation),
      maxEducationIndex: educationOptions.indexOf(preferenceForm.educationRange.maxEducation)
    });
  },

  // Tab切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ selectedTab: tab });
  },

  // 个人资料输入
  onProfileInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`profileForm.${field}`]: value
    });
  },

  // 资产信息输入
  onAssetsInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`profileForm.assets.${field}`]: value
    });
  },

  // 家庭信息输入
  onFamilyInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`profileForm.familyMembers.${field}`]: value
    });
  },

  // 父亲信息输入
  onFatherDetailInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`profileForm.familyMembers.fatherDetail.${field}`]: value
    });
  },

  // 母亲信息输入
  onMotherDetailInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`profileForm.familyMembers.motherDetail.${field}`]: value
    });
  },

  // 性别选择
  onGenderChange(e) {
    const gender = e.currentTarget.dataset.value;
    this.setData({
      'profileForm.gender': gender
    });
  },

  // 生日选择
  onBirthDateChange(e) {
    this.setData({
      'profileForm.birthDate': e.detail.value
    });
  },

  // 婚姻状况选择
  onMaritalStatusChange(e) {
    const index = e.detail.value;
    const status = this.data.maritalStatusOptions[index];
    this.setData({
      maritalStatusIndex: index,
      'profileForm.maritalStatus': status
    });
  },

  // 学历选择
  onEducationChange(e) {
    const index = e.detail.value;
    const education = this.data.educationOptions[index];
    this.setData({
      educationIndex: index,
      'profileForm.education': education
    });
  },

  // 职业选择
  onOccupationChange(e) {
    const index = e.detail.value;
    const occupation = this.data.occupationOptions[index];
    this.setData({
      occupationIndex: index,
      'profileForm.occupation': occupation
    });
  },

  // 党员状态切换
  onPartyMemberChange(e) {
    this.setData({
      'profileForm.isPartyMember': e.detail.value
    });
  },

  // 车子状况选择
  onCarStatusChange(e) {
    const index = e.detail.value;
    const status = this.data.carStatusOptions[index];
    this.setData({
      carStatusIndex: index,
      'profileForm.assets.car': status
    });
  },

  // 房子状况选择
  onHouseStatusChange(e) {
    const index = e.detail.value;
    const status = this.data.houseStatusOptions[index];
    this.setData({
      houseStatusIndex: index,
      'profileForm.assets.house': status
    });
  },

  // 省市区三级联动 - 籍贯
  onHometownRegionChange(e) {
    const [provinceIndex, cityIndex, districtIndex] = e.detail.value;
    const province = this.data.provinceOptions[provinceIndex];
    
    // 获取新省份下的城市列表
    const newCityOptions = regionSelector.getCitiesByProvince(province);
    
    // 确保城市索引在有效范围内
    const validCityIndex = Math.min(cityIndex, newCityOptions.length - 1);
    const city = newCityOptions[validCityIndex];
    
    // 获取新城市下的区县列表
    const newDistrictOptions = regionSelector.getDistrictsByCity(province, city);
    
    // 确保区县索引在有效范围内
    const validDistrictIndex = Math.min(districtIndex, newDistrictOptions.length - 1);
    const district = newDistrictOptions[validDistrictIndex];
    
    this.setData({
      hometownProvinceIndex: provinceIndex,
      hometownCityIndex: validCityIndex,
      hometownDistrictIndex: validDistrictIndex,
      hometownCityOptions: newCityOptions,
      hometownDistrictOptions: newDistrictOptions,
      hometownSelectedText: regionSelector.buildFullAddress(province, city, district)
    });
    
    // 更新表单数据
    const fullAddress = regionSelector.buildFullAddress(province, city, district);
    this.setData({
      'profileForm.hometown': fullAddress
    });
  },

  // 常见地址快速选择 - 籍贯
  onSelectCommonHometown(e) {
    const address = e.currentTarget.dataset.address;
    
    // 更新省市区索引
    const provinceIndex = this.data.provinceOptions.indexOf(address.province);
    const cityOptions = regionSelector.getCitiesByProvince(address.province);
    const cityIndex = cityOptions.indexOf(address.city);
    const districtOptions = regionSelector.getDistrictsByCity(address.province, address.city);
    const districtIndex = districtOptions.indexOf(address.district);
    
    this.setData({
      hometownProvinceIndex: provinceIndex,
      hometownCityIndex: cityIndex,
      hometownDistrictIndex: districtIndex,
      hometownCityOptions: cityOptions,
      hometownDistrictOptions: districtOptions,
      hometownSelectedText: address.fullName,
      'profileForm.hometown': address.fullName
    });
  },

  // 省市区三级联动 - 现居地
  onResidenceRegionChange(e) {
    const [provinceIndex, cityIndex, districtIndex] = e.detail.value;
    const province = this.data.provinceOptions[provinceIndex];
    
    // 获取新省份下的城市列表
    const newCityOptions = regionSelector.getCitiesByProvince(province);
    
    // 确保城市索引在有效范围内
    const validCityIndex = Math.min(cityIndex, newCityOptions.length - 1);
    const city = newCityOptions[validCityIndex];
    
    // 获取新城市下的区县列表
    const newDistrictOptions = regionSelector.getDistrictsByCity(province, city);
    
    // 确保区县索引在有效范围内
    const validDistrictIndex = Math.min(districtIndex, newDistrictOptions.length - 1);
    const district = newDistrictOptions[validDistrictIndex];
    
    this.setData({
      residenceProvinceIndex: provinceIndex,
      residenceCityIndex: validCityIndex,
      residenceDistrictIndex: validDistrictIndex,
      residenceCityOptions: newCityOptions,
      residenceDistrictOptions: newDistrictOptions,
      residenceSelectedText: regionSelector.buildFullAddress(province, city, district)
    });
    
    // 更新表单数据
    const fullAddress = regionSelector.buildFullAddress(province, city, district);
    this.setData({
      'profileForm.currentResidence': fullAddress
    });
  },

  // 常见地址快速选择 - 现居地
  onSelectCommonResidence(e) {
    const address = e.currentTarget.dataset.address;
    
    // 更新省市区索引
    const provinceIndex = this.data.provinceOptions.indexOf(address.province);
    const cityOptions = regionSelector.getCitiesByProvince(address.province);
    const cityIndex = cityOptions.indexOf(address.city);
    const districtOptions = regionSelector.getDistrictsByCity(address.province, address.city);
    const districtIndex = districtOptions.indexOf(address.district);
    
    this.setData({
      residenceProvinceIndex: provinceIndex,
      residenceCityIndex: cityIndex,
      residenceDistrictIndex: districtIndex,
      residenceCityOptions: cityOptions,
      residenceDistrictOptions: districtOptions,
      residenceSelectedText: address.fullName,
      'profileForm.currentResidence': address.fullName
    });
  },

  // 籍贯选择（保留原有功能兼容性）
  onHometownChange(e) {
    const index = e.detail.value;
    const hometown = this.data.hometownOptions[index];
    this.setData({
      hometownIndex: index,
      'profileForm.hometown': hometown
    });
  },

  // 现居地选择（保留原有功能兼容性）
  onResidenceChange(e) {
    const index = e.detail.value;
    const residence = this.data.residenceOptions[index];
    this.setData({
      residenceIndex: index,
      'profileForm.currentResidence': residence
    });
  },

  // 择偶标准输入
  onPreferenceInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`preferenceForm.${field}`]: value
    });
  },

  // 年龄范围改变
  onAgeRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`preferenceForm.ageRange.${type}`]: value
    });
  },

  // 身高范围改变
  onHeightRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`preferenceForm.heightRange.${type}`]: value
    });
  },

  // 体重范围改变
  onWeightRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`preferenceForm.weightRange.${type}`]: value
    });
  },

  // 收入范围改变
  onIncomeRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`preferenceForm.incomeRange.${type}`]: value
    });
  },

  // 最低学历选择
  onMinEducationChange(e) {
    const index = e.detail.value;
    const education = this.data.educationOptions[index];
    this.setData({
      minEducationIndex: index,
      'preferenceForm.educationRange.minEducation': education
    });
  },

  // 最高学历选择
  onMaxEducationChange(e) {
    const index = e.detail.value;
    const education = this.data.educationOptions[index];
    this.setData({
      maxEducationIndex: index,
      'preferenceForm.educationRange.maxEducation': education
    });
  },

  // 职业要求选择
  onOccupationRequireChange(e) {
    const value = e.currentTarget.dataset.value;
    let { occupationRequire } = this.data.preferenceForm;
    
    if (occupationRequire.includes(value)) {
      occupationRequire = occupationRequire.filter(item => item !== value);
    } else {
      occupationRequire = [...occupationRequire, value];
    }
    
    this.setData({
      'preferenceForm.occupationRequire': occupationRequire
    });
  },

  // 籍贯要求选择
  onHometownRequiredChange(e) {
    const value = e.currentTarget.dataset.value;
    let { hometownRequired } = this.data.preferenceForm;
    
    if (hometownRequired.includes(value)) {
      hometownRequired = hometownRequired.filter(item => item !== value);
    } else {
      hometownRequired = [...hometownRequired, value];
    }
    
    this.setData({
      'preferenceForm.hometownRequired': hometownRequired
    });
  },

  // 现居地要求选择
  onResidenceRequiredChange(e) {
    const value = e.currentTarget.dataset.value;
    let { currentResidenceRequired } = this.data.preferenceForm;
    
    if (currentResidenceRequired.includes(value)) {
      currentResidenceRequired = currentResidenceRequired.filter(item => item !== value);
    } else {
      currentResidenceRequired = [...currentResidenceRequired, value];
    }
    
    this.setData({
      'preferenceForm.currentResidenceRequired': currentResidenceRequired
    });
  },

  // 性格特征输入
  onPersonalityTraitInput(e) {
    this.setData({
      personalityTraitInput: e.detail.value
    });
  },

  // 添加性格特征
  onAddPersonalityTrait() {
    const input = this.data.personalityTraitInput.trim();
    if (!input) {
      wx.showToast({
        title: '请输入性格特征',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.preferenceForm.personalityTraits.includes(input)) {
      wx.showToast({
        title: '已存在该特征',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      'preferenceForm.personalityTraits': [...this.data.preferenceForm.personalityTraits, input],
      personalityTraitInput: ''
    });
  },

  // 删除性格特征
  onRemovePersonalityTrait(e) {
    const index = e.currentTarget.dataset.index;
    const traits = this.data.preferenceForm.personalityTraits;
    traits.splice(index, 1);
    
    this.setData({
      'preferenceForm.personalityTraits': traits
    });
  },

  // 其他要求输入
  onOtherRequiredInput(e) {
    this.setData({
      otherRequiredInput: e.detail.value
    });
  },

  // 添加其他要求
  onAddOtherRequired() {
    const input = this.data.otherRequiredInput.trim();
    if (!input) {
      wx.showToast({
        title: '请输入其他要求',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.preferenceForm.otherRequired.includes(input)) {
      wx.showToast({
        title: '已存在该要求',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      'preferenceForm.otherRequired': [...this.data.preferenceForm.otherRequired, input],
      otherRequiredInput: ''
    });
  },

  // 删除其他要求
  onRemoveOtherRequired(e) {
    const index = e.currentTarget.dataset.index;
    const required = this.data.preferenceForm.otherRequired;
    required.splice(index, 1);
    
    this.setData({
      'preferenceForm.otherRequired': required
    });
  },

  // 提交个人资料
  async onSubmitProfile() {
    try {
      // 验证必填字段
      if (!this.validateProfile()) {
        return;
      }
      
      this.setData({ submitting: true });
      
      // 调用API保存资料
      await api.syncUserProfile(this.data.profileForm);
      
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('保存个人资料失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 提交择偶标准
  async onSubmitPreference() {
    try {
      this.setData({ submitting: true });
      
      // 调用API保存择偶标准
      await api.syncMatePreference(this.data.preferenceForm);
      
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('保存择偶标准失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 验证个人资料
  validateProfile() {
    const { profileForm } = this.data;
    
    if (!profileForm.name.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return false;
    }
    
    if (!profileForm.gender) {
      wx.showToast({ title: '请选择性别', icon: 'none' });
      return false;
    }
    
    if (!profileForm.birthDate) {
      wx.showToast({ title: '请选择生日', icon: 'none' });
      return false;
    }
    
    if (!profileForm.height || profileForm.height < 100 || profileForm.height > 250) {
      wx.showToast({ title: '请输入正确的身高', icon: 'none' });
      return false;
    }
    
    if (!profileForm.weight || profileForm.weight < 60 || profileForm.weight > 300) {
      wx.showToast({ title: '请输入正确的体重', icon: 'none' });
      return false;
    }
    
    if (!profileForm.maritalStatus) {
      wx.showToast({ title: '请选择婚姻状况', icon: 'none' });
      return false;
    }
    
    if (!profileForm.education) {
      wx.showToast({ title: '请选择学历', icon: 'none' });
      return false;
    }
    
    if (!profileForm.occupation) {
      wx.showToast({ title: '请选择职业', icon: 'none' });
      return false;
    }
    
    if (!profileForm.assets.annualIncome || profileForm.assets.annualIncome < 0) {
      wx.showToast({ title: '请输入正确的年收入', icon: 'none' });
      return false;
    }
    
    if (!profileForm.hometown) {
      wx.showToast({ title: '请选择籍贯', icon: 'none' });
      return false;
    }
    
    if (!profileForm.currentResidence) {
      wx.showToast({ title: '请选择现居地', icon: 'none' });
      return false;
    }
    
    return true;
  }
});